package com.zsp.comic.config.handler;

import com.alibaba.fastjson.JSON;
import com.zsp.comic.entity.JsonResult;
import com.zsp.comic.entity.SelfUserEntity;
import com.zsp.comic.service.UserService;
import com.zsp.comic.util.JWTTokenUtil;
import com.zsp.comic.util.ResultTool;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;


import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author gan
 * @create 2020-12-04 15:24
 */
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private UserService userService;

    //登录成功之后会被调用
    //Authentication用来封装我们的认证信息，包括发起认证请求里的认证信息（IP，Session，以及认证通过之后User
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException, ServletException {

//        String username = request.getParameter("username");
//        String password = request.getParameter("password");
//        System.out.println("username:"+username+",password:"+password);

        //可以更新用户表上次登录时间、更新人、更新时间等字段，这里就没有怎么做了
//        org.springframework.security.core.userdetails.User userDetails = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        User user = userDao.getUserByUsername(userDetails.getUsername());


        Map<String, Object> map = new HashMap<>();
        User user = (User) auth.getPrincipal();
        com.zsp.comic.entity.User myUser = userService.getUserByUsername(user.getUsername());

        SelfUserEntity selfUserEntity = new SelfUserEntity(myUser.getId(), user.getUsername(), user.getAuthorities());

//        String authority = userService.getUserAuthorityById(myUser.getId());

//        Set<String> roles =  new HashSet<>();
//
//        if (!CollectionUtils.isEmpty(authorities)){
//            for (GrantedAuthority authority : authorities){
//                String roleName = authority.getAuthority();
//                roles.add(roleName);
//            }
//        }
//
//        JwtBuilder jwtBuilder = Jwts.builder()
//                .setId(Integer.toString(myUser.getId()))         //设置用户id
//                .setSubject(user.getUsername())   //设置用户名
//                .claim("authorities", JSON.toJSONString(user.getAuthorities()))
//                .setIssuedAt(new Date())
//                .signWith(SignatureAlgorithm.HS256,"9277"); //这里似乎只能是数字作为密钥

        String token = JWTTokenUtil.createAccessToken(selfUserEntity);

//        String token = jwtBuilder.compact();

        map.put("userId", myUser.getId());
        map.put("username", user.getUsername());
        map.put("authorities", user.getAuthorities());
        map.put("token",token);
        map.put("registerTime",myUser.getRegisterTime());

        //返回json数据
        response.setContentType("text/json;charset=utf-8");
        JsonResult result = ResultTool.success(map);
        response.getWriter().write(JSON.toJSONString(result));


        //此处还可以进行一些处理，比如登录成功之后可能需要返回给前台当前用户有哪些菜单权限，
        //进而前台动态的控制菜单的显示等，具体根据自己的业务需求进行扩展
    }
}
